package com.health.viewscontrols.medical.device.waist;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.health.httpbean.model.BpModel;
import com.health.httpbean.model.WaistBean;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.inuker.bluetooth.library.Contast;
import com.inuker.bluetooth.library.ZBleManager;
import com.inuker.bluetooth.library.interFace.IBleConnectStatusListener;
import com.inuker.bluetooth.library.interFace.IBleIndicateListener;
import com.inuker.bluetooth.library.interFace.IBleWriteListener;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.nova.health.ble.HexUtil;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.views.twj.TwjConstans;
import com.novabluetooth.views.twj.ZHexUtil;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 腰臀比
 */
public class WaistActivity extends BaseDeviceActivity {

    public final static UUID UUID_SERVICE =
            UUID.fromString("0783b03e-8535-b5a0-7140-a304d2495cb7");
    public final static UUID UUID_NOTIFY =
            UUID.fromString("0783b03e-8535-b5a0-7140-a304d2495cb8");

    // 1 测量腰围； 2 测量臀围
    private int clType = 1;
    // 数据解析完成
    protected boolean isParseDataSuccess = false;

    @Override
    public void doBusiness() {
        tv_operation_tips.setText("请使用健康尺测量腰围、臀围，拉至所需长度后按下健康尺上的“对号”键！");


        BleManager.getInstance().init(getApplication());

        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setDeviceMac(deviceEnum.getMac())
                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒；小于等于0表示不限制扫描时间
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);

    }

    @Override
    public void startDevice() {
//        double waist1 = 68.23;
//        double waist = 61.23;
//        double ratio = 0.78;
//        DeviceShowSaveData.getDataShow(waist1 + ";" + waist + ";" + ratio + ";", "WAIST");
//
//        WaistBean waistBean = new WaistBean();
//        waistBean.setWaist(waist1 + "");
//        waistBean.setHip(waist + "");
//        waistBean.setRatio(ratio + "");
//        DeviceShowSaveData.saveWaist(GsonUtils.toJson(waistBean));

        if (!isConnected) {
            isParseDataSuccess = false;
//            showProgressDialog("正在连接腰臀比");
            BleManager.getInstance().scan(new BleScanCallback() {
                @Override
                public void onScanStarted(boolean success) {
                }

                @Override
                public void onLeScan(BleDevice bleDevice) {
                    super.onLeScan(bleDevice);
                }

                @Override
                public void onScanning(BleDevice bleDevice) {
                    if (bleDevice != null && bleDevice.getMac() != null && deviceEnum.getMac().equals(bleDevice.getMac())) {
                        connDevice();
                    }
                }

                @Override
                public void onScanFinished(List<BleDevice> scanResultList) {

                }
            });
        } else {
            blueToothState.setText("蓝牙已连接");
            clTypeFn(1);
        }
    }

    private void clTypeFn(int clType) {
        if (clType == 1) {
//            iv_left1.setVisibility(View.VISIBLE);
//            iv_right1.setVisibility(View.VISIBLE);
//            iv_left2.setVisibility(View.GONE);
//            iv_right2.setVisibility(View.GONE);
//            tv_cl_title.setText("测量腰围");
            tv_result.setText("请使用健康尺测量腰围，拉至所需长度后按下健康尺上的“对号”键！");
//            tv_cl_data.setText("");
        } else {
//            iv_left1.setVisibility(View.GONE);
//            iv_right1.setVisibility(View.GONE);
//            iv_left2.setVisibility(View.VISIBLE);
//            iv_right2.setVisibility(View.VISIBLE);
//            tv_cl_title.setText("测量臀围");
            if (waist1 != 0) {
                tv_result.setText("腰围测量成功：" + waist1 +"cm，" + "请使用健康尺测量臀围，拉至所需长度后按下健康尺上的“对号”键！");
            } else {
                tv_result.setText("请使用健康尺测量臀围，拉至所需长度后按下健康尺上的“对号”键！");
            }

        }
        this.clType = clType;
    }

    private void connDevice() {
        showProgressDialog("开始连接设备");
        BleManager.getInstance().connect(deviceEnum.getMac(), new BleGattCallback() {
            @Override
            public void onStartConnect() {
                blueToothState.setText("开始连接蓝牙");
                Log.e(TAG, "*********开始连接**************");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG, "*********连接失败**************" + exception.toString());
                isConnected = false;
                blueToothState.setText("蓝牙连接失败");
                cancelProgressDialog();
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                Log.e(TAG, "*********连接成功**************");
                isConnected = true;
                blueToothState.setText("蓝牙已连接");
                clTypeFn(1);
                cancelProgressDialog();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        bleNotify(bleDevice, UUID_SERVICE.toString(), UUID_NOTIFY.toString());
                    }
                }, 500);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                Log.e(TAG, "*********连接中断**************" + status);
                isConnected = false;
                blueToothState.setText("蓝牙已断开");
                cancelProgressDialog();
            }
        });
    }

    private void bleNotify(BleDevice bleDevice, String uuid_service, String uuid_characteristic_notify) {
        BleManager.getInstance().notify(
                bleDevice,
                uuid_service,
                uuid_characteristic_notify,
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        // 打开通知操作成功
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        // 打开通知操作失败
                    }

                    @Override
                    public void onCharacteristicChanged(final byte[] data) {
                        // 打开通知后，设备发过来的数据将在这里出现
                        Log.e(TAG, "onCharacteristicChanged: " + "收到data==" + Arrays.toString(data));
                        Log.e(TAG, "onCharacteristicChanged: "  +  com.clj.fastble.utils.HexUtil.formatHexString(data));
                        try {
                            update(HexUtil.bytesToHexString(data));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    public static String convertHexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < hex.length() - 1; i += 2) {
            String output = hex.substring(i, (i + 2));
            int decimal = Integer.parseInt(output, 16);
            sb.append((char) decimal);
            temp.append(decimal);
        }
        return sb.toString();
    }

    private double waist1 = 0;
    @Override
    public void update(String hexStr) {
        if (TextUtils.isEmpty(hexStr) || hexStr.length() < 9 ) {
            return;
        }
        String cmd = hexStr.substring(10, 12);
        String data = hexStr.substring(0, 8);
        Log.e(TAG, "update: " + cmd );
        Log.e(TAG, "update: " + Integer.parseInt(data, 16));
        if ("53".equals(cmd)) {
            double waist = Integer.parseInt(convertHexToString(data)) / 10.0;
            Log.e(TAG, "update: " +  waist);
//            tv_cl_data.setText(waist + "cm");
            if (clType == 1) {
                waist1 = waist;
                clTypeFn(2);
            } else if (clType == 2) {
//                String tvWaist = tv_waist.getText().toString().trim().replace("cm", "");
                double ratio = formatDouble4(waist1 / waist);
//                tv_hip.setText(waist + "cm");
//                tv_ratio.setText(CompUtil.formatDouble4(ratio) + "");
//                ll_main.setVisibility(View.VISIBLE);
//                ll_waist.setVisibility(View.GONE);
                String results = "腰围：" + waist1 + "cm，臀围：" + waist +"cm，腰臀比：" + ratio;
                tv_result.setText("测量结果：\n        " + results);
                tv_state.setText("获取测量结果成功");
                DeviceShowSaveData.getDataShow(waist1 + ";" + waist + ";" + ratio + ";", "WAIST");

                WaistBean waistBean = new WaistBean();
                waistBean.setWaist(waist1 + "");
                waistBean.setHip(waist + "");
                waistBean.setRatio(ratio + "");
                DeviceShowSaveData.saveWaist(GsonUtils.toJson(waistBean));
            }
        }
    }

    @Override
    public void disconnectDevice() {
        try {
            clTypeFn(2);
            BleManager.getInstance().cancelScan();
            BleManager.getInstance().disconnectAllDevice();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static double formatDouble4(double value) {
        DecimalFormat df = new DecimalFormat("#.00");
        String format = df.format(value);
        return Double.parseDouble(format);
    }

}
